package com.eb.buybuybuy.filter;

import com.eb.buybuybuy.constant.Configuration;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/api/*")
public class Filter2_Login implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String path = request.getServletPath();
        if (request.getPathInfo() != null) {
            path += request.getPathInfo();
        }

        HttpSession session = request.getSession();
        Object userId = session.getAttribute("userId");

        if (userId != null) {
            // 已登录 放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        for (String p : Configuration.whitePath) {
            if (path.equals(p)) {
                // 在白名单中 放行
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
        }

        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setStatus(403);
    }
}
